package com.example.aircraftwar.application.loginorregister;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.aircraftwar.R;
import com.example.aircraftwar.application.MainActivity;
import com.example.aircraftwar.application.network.NetConn;
import com.example.aircraftwar.scorelist.ScoreRankActivity;
import com.example.aircraftwar.startgame.StartGameActivity;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import java.io.IOException;
import java.util.Objects;

public class LoginOrRegisterActivity extends AppCompatActivity {
    private static Button loginButton;
    private static Button registerButton;
    private EditText userNameText;
    private EditText passWordText;
    public static String userName = null;
    private String passWord = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_or_register);
        userNameText = findViewById(R.id.usernametext);
        passWordText = findViewById(R.id.passwordtext);
        loginButton = findViewById(R.id.loginbutton);
        loginButton.setBackgroundResource(R.drawable.button);
        registerButton = findViewById(R.id.registerbutton);
        registerButton.setBackgroundResource(R.drawable.button);
        loginButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                    loginButton.setBackgroundResource(R.drawable.buttonclick);
                }else if(motionEvent.getAction() == MotionEvent.ACTION_UP){
                    loginButton.setBackgroundResource(R.drawable.button);
                    userName = userNameText.getText().toString().trim();
                    passWord = passWordText.getText().toString().trim();
                    login(userName,passWord);
                }
                return false;
            }
        });
        registerButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                    registerButton.setBackgroundResource(R.drawable.buttonclick);
                }else if(motionEvent.getAction() == MotionEvent.ACTION_UP){
                    registerButton.setBackgroundResource(R.drawable.button);
                    userName = userNameText.getText().toString().trim();
                    passWord = passWordText.getText().toString().trim();
                    register(userName,passWord);
                }
                return false;
            }
        });
        new Thread(new NetConn()).start();
    }

    private void register(String userName,String passWord) {
        if (userName.equals("") || passWord.equals("")) {
            Toast.makeText(LoginOrRegisterActivity.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
        } else {
            //向服务器发送用户名和密码
            new Thread(() -> {
                try {
                    NetConn.writer.println(initJson("register",userName,passWord).toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }).start();
            //接受服务器的回复
            new Thread(() -> {
                String reply = "";
                try {
                    while (!Objects.equals(reply, "success")) {
                        while ((reply = NetConn.reader.readLine()) != null) {
                            Log.i("net", "get msg from server");
                            JSONObject jsonObject = net.sf.json.JSONObject.fromObject(reply);
                            reply = jsonObject.getString("msg");
                            if (reply.equals("null")) {
                                runOnUiThread(()->{
                                    Toast.makeText(this, "用户名不能包含空格", Toast.LENGTH_SHORT).show();
                                });
                            } else if (reply.equals("existed")) {
                                runOnUiThread(()->{
                                    Toast.makeText(this, "该用户名已存在", Toast.LENGTH_SHORT).show();
                                });
                            } else if (reply.equals("success")){
                                Log.d("reg", "注册成功");
//                            new Thread(() -> NetConn.writer.println("wait")).start();
                                runOnUiThread(()->{
                                    // 跳转到选择游戏难度界面
                                    Intent intent = new Intent();
                                    intent.setClass(this, StartGameActivity.class);
                                    startActivity(intent);
                                    finish();
                                    Toast.makeText(this, "注册成功,已自动登录", Toast.LENGTH_SHORT).show();
                                });
                            } else {
                                runOnUiThread(()->{
                                    Toast.makeText(this, "注册失败", Toast.LENGTH_SHORT).show();
                                });
                            }
                            break;
                        }
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    private void login(String userName,String passWord) {
        if (userName.equals("") || passWord.equals("")) {
            Toast.makeText(LoginOrRegisterActivity.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
        } else {
            //向服务器发送用户名和密码
            new Thread(() -> {
                try {
                    NetConn.writer.println(initJson("login",userName,passWord).toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }).start();
            //接受服务器的回复
            new Thread(() -> {
                String reply = "";
                try {
                        while ((reply = NetConn.reader.readLine()) != null) {
                            Log.i("net", "get msg from server");
                            JSONObject jsonObject = JSONObject.fromObject(reply);
                            reply = jsonObject.getString("msg");
                            System.out.println(reply);
                            if (reply.equals("fail") || reply.equals("notexist")) {
                                runOnUiThread(()->{
                                    Toast.makeText(this, "不存在该用户，请点击注册", Toast.LENGTH_SHORT).show();
                                });
                            } else if (reply.equals("incorrect")) {
                                runOnUiThread(()->{
                                    Toast.makeText(this, "用户名或密码不正确", Toast.LENGTH_SHORT).show();
                                });
                            } else if (reply.equals("success")){
//                            new Thread(() -> NetConn.writer.println("wait")).start();
                                Log.d("reg", "登录成功");
                                runOnUiThread(()->{
                                    // 跳转到选择游戏难度界面
                                    Intent intent = new Intent();
                                    intent.setClass(this, StartGameActivity.class);
                                    startActivity(intent);
                                    finish();
                                    Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                                });
                            } else {
                                runOnUiThread(()->{
                                    Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
                                });
                            }
                        break;
                        }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    private JSONObject initJson(String request,String userName,String passWord) throws JSONException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("request",request);
        jsonObject.put("username", userName);
        jsonObject.put("password", passWord);
        return jsonObject;
    }

    private JSONObject initJsonbye() throws JSONException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("request","bye");
        return jsonObject;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //exit();
            new Thread(() -> {
                NetConn.writer.println(initJsonbye().toString());
            }).start();
            Intent intent = new Intent(LoginOrRegisterActivity.this, MainActivity.class);
            startActivity(intent);
            return false;
        }
        else {
            return super.onKeyDown(keyCode, event);
        }
    }
}